import React, { useState, useEffect } from 'react';
import { Layout, Menu, Avatar, Dropdown, Space, App, Typography } from 'antd';
import {
    UserOutlined,
    VideoCameraOutlined,
    LogoutOutlined,
    DownOutlined,
    CheckCircleOutlined,
    CrownOutlined,
    HistoryOutlined
} from '@ant-design/icons';
import { useNavigate, Link, Outlet, useLocation } from 'react-router-dom';
import axios from 'axios';
import { getFullMediaUrl } from '../utils/config';
import { UserWebSocketProvider } from '../contexts/UserWebSocketContext';

const { Header, Sider, Content } = Layout;

const DashboardContent: React.FC = () => {
    const { notification } = App.useApp();
    const navigate = useNavigate();
    const location = useLocation();
    const [displayName, setDisplayName] = useState(localStorage.getItem('username') || '用户');
    const [avatarUrl, setAvatarUrl] = useState<string>('');
    const [welcomeShown, setWelcomeShown] = useState(false);
    const [collapsed, setCollapsed] = useState(false);

    // Load user profile data and show welcome message
    useEffect(() => {
        const loadUserProfile = async () => {
            const token = localStorage.getItem('authToken');
            if (!token) return;

            try {
                const response = await axios.get('/api/auth/user/', {
                    headers: { 'Authorization': `Token ${token}` }
                });

                // 直接使用用户名
                setDisplayName(response.data.username);

                if (response.data.profile?.avatar) {
                    // 确保URL正确处理，添加域名前缀
                    setAvatarUrl(getFullMediaUrl(response.data.profile.avatar) || '');
                }
            } catch (error) {
                console.error('Failed to load user profile:', error);
            }
        };

        // 检查是否有欢迎信息需要显示（只显示一次）
        const welcomeMessage = localStorage.getItem('welcomeMessage');
        console.log('UserDashboard: 检查欢迎信息:', welcomeMessage);
        if (welcomeMessage && !welcomeShown) {
            console.log('UserDashboard: 准备显示欢迎信息');
            setWelcomeShown(true);
            // 立即清除localStorage，防止重复显示
            localStorage.removeItem('welcomeMessage');

            // 延迟显示欢迎信息，确保页面已加载
            setTimeout(() => {
                console.log('UserDashboard: 显示欢迎通知');
                notification.success({
                    message: '登录成功！',
                    description: welcomeMessage,
                    duration: 4,
                    placement: 'topRight',
                    icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
                });
                console.log('UserDashboard: 欢迎通知已显示');
            }, 500);
        } else {
            console.log('UserDashboard: 没有找到欢迎信息或已经显示过');
        }

        loadUserProfile();
    }, []);

    // Listen for profile updates
    useEffect(() => {
        const handleProfileUpdate = (event: any) => {
            console.log('UserDashboard received profile update event:', event.detail);
            if (event.detail?.displayName) {
                console.log('Updating display name to:', event.detail.displayName);
                setDisplayName(event.detail.displayName);
            }
            if (event.detail?.avatarUrl) {
                console.log('Updating avatar URL to:', event.detail.avatarUrl);
                // 确保URL正确处理，添加域名前缀
                setAvatarUrl(getFullMediaUrl(event.detail.avatarUrl) || '');
            }
        };

        window.addEventListener('userProfileUpdated', handleProfileUpdate);

        return () => {
            window.removeEventListener('userProfileUpdated', handleProfileUpdate);
        };
    }, []);

    const handleLogout = () => {
        localStorage.removeItem('authToken');
        localStorage.removeItem('username');
        navigate('/');
    };

    const menuItems = [
        {
            key: '/dashboard/account',
            icon: <UserOutlined />,
            label: <Link to="/dashboard/account">个人设置</Link>,
        },
        {
            key: '/dashboard/face-management',
            icon: <VideoCameraOutlined />,
            label: <Link to="/dashboard/face-management">人脸管理</Link>,
        },
        {
            key: '/dashboard/my-logs',
            icon: <HistoryOutlined />,
            label: <Link to="/dashboard/my-logs">我的访问记录</Link>,
        },
    ];

    const dropdownMenu = {
        items: [
            {
                key: 'logout',
                icon: <LogoutOutlined />,
                label: '退出登录',
                onClick: handleLogout,
            },
        ]
    };

    // Determine selected key based on current path
    const selectedKey = menuItems.find(item => location.pathname.startsWith(item.key))?.key || '/dashboard/account';

    return (
        <Layout style={{ minHeight: '100vh' }}>
            <Sider collapsible collapsed={collapsed} onCollapse={setCollapsed} width={250}>
                <div style={{
                    height: 64,
                    margin: 16,
                    background: 'rgba(255, 255, 255, 0.1)',
                    borderRadius: 6,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    color: 'white',
                    fontWeight: 'bold',
                    overflow: 'hidden',
                    position: 'relative',
                    transition: 'all 0.2s',
                }}>
                    <span style={{
                        opacity: collapsed ? 1 : 0,
                        transition: 'opacity 0.2s',
                        position: 'absolute',
                    }}>
                        <CrownOutlined style={{ fontSize: 24 }} />
                    </span>
                    <span style={{
                        opacity: collapsed ? 0 : 1,
                        transition: 'opacity 0.2s',
                        fontSize: 16,
                    }}>
                        智能门禁管理系统
                    </span>
                </div>
                <Menu theme="dark" mode="inline" selectedKeys={[selectedKey]} items={menuItems} />
            </Sider>
            <Layout>
                <Header style={{ padding: '0 24px', background: '#fff', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Typography.Title level={4} style={{ margin: 0 }}>
                        用户控制台
                    </Typography.Title>
                    <Dropdown menu={dropdownMenu} trigger={['click']}>
                        <a onClick={(e) => e.preventDefault()}>
                            <Space>
                                <Avatar
                                    src={avatarUrl || null}
                                    icon={!avatarUrl ? <UserOutlined /> : undefined}
                                />
                                <span>{displayName}</span>
                                <DownOutlined />
                            </Space>
                        </a>
                    </Dropdown>
                </Header>
                <Content style={{ margin: '24px 16px', padding: 24, minHeight: 280, background: '#fff' }}>
                    {/* Nested routes will be rendered here */}
                    <Outlet />
                </Content>
            </Layout>
        </Layout>
    );
};

const UserDashboard: React.FC = () => {
    const { message } = App.useApp();
    return (
        <UserWebSocketProvider messageApi={message}>
            <DashboardContent />
        </UserWebSocketProvider>
    );
};

export default UserDashboard;